package com.xcjw.com;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMClientListener;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMMultiDeviceListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.xcjw.com.Activity.LoginActivity;
import com.xcjw.com.Base.MyActivityManager;
import com.xcjw.com.Base.Myapplication;
import com.xcjw.com.Base.StackManager;
import com.xcjw.com.CallBack.CallBackUtils;
import com.xcjw.com.CallBack.FragmentCallback;
import com.xcjw.com.Fragment.HomeFragment;
import com.xcjw.com.Fragment.MyconversationFragment;
import com.xcjw.com.Hy.Constant;
import com.xcjw.com.Hy.DemoHelper;
import com.xcjw.com.Utils.FileUtils;
import com.xcjw.com.Utils.StatusBarUtil;
import com.xcjw.com.View.CustomDialog;
import com.xcjw.com.View.NoScrollViewPager;
import com.xcjw.com.db.InviteMessgeDao;
import com.xcjw.com.db.UserDao;
import com.xcjw.com.runtimepermissions.PermissionsManager;
import com.xcjw.com.runtimepermissions.PermissionsResultAction;
import com.xcjw.com.ui.ChatActivity;
import com.xcjw.com.ui.ContactListFragment;
import com.xcjw.com.ui.GroupsActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class
MainActivity extends AppCompatActivity implements FragmentCallback {

      @BindView(R.id.viewpager)
      NoScrollViewPager viewpager;
      @BindView(R.id.layout)
      TabLayout layout;
      @BindView(R.id.image)
      ImageView image;
//      @BindView(R.id.txt_left_title)
//      TextView txtLeftTitle;
//      @BindView(R.id.txt_main_title)
//      TextView txtMainTitle;
//      @BindView(R.id.txt_right_titleS)
//      TextView txtRightTitleS;
//      @BindView(R.id.txt_right_title)
//      TextView txtRightTitle;
//      @BindView(R.id.simple_toolbar)
//      SimpleTool simpleToolbar;

      private ArrayList<String> listTitles;
      private ArrayList<Fragment> fragmentList;
      private int[] tabIcons = {
                R.drawable.selector_mall,
                R.drawable.selector_home,
      };
      private ImageView tabimage1;
      private ImageView indica1;
      private TextView tabtext1;
      private ImageView tabimage2;
      private ImageView indica2;
      private TextView tabtext2;
      private ImageView tabimage3;
      private ImageView indica3;
      private TextView tabtext3;
      private InviteMessgeDao inviteMessgeDao;
      private MyconversationFragment fragment;
      private ContactListFragment fragment1;
      private LocalBroadcastManager broadcastManager;
      private BroadcastReceiver broadcastReceiver;
      private int height;
      private CustomDialog dialog;

      @TargetApi(Build.VERSION_CODES.M)
      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
//            StatusBarUtil.setRootViewFitsSystemWindows(this, false);
            StatusBarUtil.setTranslucentStatus(this);
            setContentView(R.layout.activity_main);
            ButterKnife.bind(this);
            initData();
            requestPermissions();
            CallBackUtils.setCallBack(this);
            StackManager.getInstance().isExists(MainActivity.class);
            StackManager.getInstance().pushActivity(this);
//            if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
//                  //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
//                  //这样半透明+白=灰, 状态栏的文字能看得清
//                  StatusBarUtil.setStatusBarColor(this,0x55000000);
//            }


      }

      @Override
      public void ondatechange(int position) {
            if (position == 6) {
                  runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                              if (MyActivityManager.getInstance().getCurrentActivity() instanceof MainActivity) {
                                    Myapplication.editor.putBoolean("isLogin", false).commit();
                                    Myapplication.editor.putBoolean("isconflected",true).commit();
                                    FileUtils.saveObject(MyActivityManager.getInstance().getCurrentActivity(), "loginUser", "");
                                    FileUtils.saveObject(MyActivityManager.getInstance().getCurrentActivity(), "User", "");
                                    DemoHelper.getInstance().logout(false, null);
                                    MainActivity.this.finish();
                                    startActivity(new Intent(MyActivityManager.getInstance().getCurrentActivity(), LoginActivity.class));
                                    CallBackUtils.doCallBackMethod(10);
                              } else {
                                    Myapplication.editor.putBoolean("isLogin", false).commit();
                                    Myapplication.editor.putBoolean("isconflected",true).commit();
                                    FileUtils.saveObject(MyActivityManager.getInstance().getCurrentActivity(), "loginUser", "");
                                    FileUtils.saveObject(MyActivityManager.getInstance().getCurrentActivity(), "User", "");
                                    DemoHelper.getInstance().logout(false, null);
                                    MainActivity.this.finish();
                                    Myapplication.getInstance().exitactivity();
                                    startActivity(new Intent(MyActivityManager.getInstance().getCurrentActivity(), LoginActivity.class));
                                    MyActivityManager.getInstance().getCurrentActivity().finish();
                              }
                        }
                  });
            }
      }

      public class MyPagerAdapter extends FragmentPagerAdapter {

            private ArrayList<Fragment> mFragmentList;

            public void setFragments(ArrayList<Fragment> fragments) {
                  mFragmentList = fragments;
            }

            public MyPagerAdapter(FragmentManager fm) {
                  super(fm);
            }

            @Override
            public Fragment getItem(int position) {
                  Fragment fragment = mFragmentList.get(position);
                  return fragment;
            }

            @Override
            public int getCount() {
                  return mFragmentList.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                  return listTitles.get(position).toString();
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                  // container.removeView(fragmentList.get(position));
            }
      }

      private void initData() {
            listTitles = new ArrayList<>();
            listTitles.add("会话");
            listTitles.add("通讯录");
            listTitles.add("通讯录");
            fragmentList = new ArrayList<>();
            fragmentList.add(new HomeFragment());
            fragment = new MyconversationFragment();
            fragmentList.add(fragment);
            fragment1 = new ContactListFragment();
            fragmentList.add(fragment1);
            MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
            adapter.setFragments(fragmentList);
            viewpager.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            layout.setupWithViewPager(viewpager);
            layout.getTabAt(0).setCustomView(R.layout.tab_item_view);
            layout.getTabAt(1).setCustomView(R.layout.tab_item_view1);
            layout.getTabAt(2).setCustomView(R.layout.tab_item_view2);
            tabimage1 = (ImageView) layout.getTabAt(0).getCustomView().findViewById(R.id.imageview);
            indica1 = (ImageView) layout.getTabAt(0).getCustomView().findViewById(R.id.daiban_red);
            tabtext1 = (TextView) layout.getTabAt(0).getCustomView().findViewById(R.id.textview);
            tabimage2 = (ImageView) layout.getTabAt(1).getCustomView().findViewById(R.id.imageview1);
            indica2 = (ImageView) layout.getTabAt(1).getCustomView().findViewById(R.id.daiban_red1);
            tabtext2 = (TextView) layout.getTabAt(1).getCustomView().findViewById(R.id.textview1);
            tabimage3 = (ImageView) layout.getTabAt(2).getCustomView().findViewById(R.id.imageview2);
            indica3 = (ImageView) layout.getTabAt(2).getCustomView().findViewById(R.id.daiban_red2);
            tabtext3 = (TextView) layout.getTabAt(2).getCustomView().findViewById(R.id.textview2);
            init();
            layout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                  @Override
                  public void onTabSelected(TabLayout.Tab tab) {
//                        ((MainActivity) mActivity).toobarTitle.setText(tab.getText());
                  }

                  @Override
                  public void onTabUnselected(TabLayout.Tab tab) {

                  }

                  @Override
                  public void onTabReselected(TabLayout.Tab tab) {

                  }
            });
            int result = 0;
            int resourceId = this.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                  result = this.getResources().getDimensionPixelSize(resourceId);
            }
            WindowManager wm = this.getWindowManager();
            Point point = new Point();
            wm.getDefaultDisplay().getSize(point);
            int width = point.x;
            height = point.y;

            final int finalResult = result;
            viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                  @Override
                  public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                        switch (position) {
                              case 0:
                                    image.setVisibility(View.GONE);

                                    // StatusBarUtil.setStatusBarDarkTheme(MainActivity.this, true);
                                    //  simpleToolbar.setVisibility(View.VISIBLE);
                                    //  StatusBarUtil.setStatusBarColor(MainActivity.this,R.color.color_transparent);
                                    break;
                              case 1:
                                    image.setVisibility(View.VISIBLE);
                                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) image.getLayoutParams();
                                    params.height = finalResult;
                                    params.width = height;
                                    image.setLayoutParams(params);

                                    //  simpleToolbar.setVisibility(View.GONE);
                                    // StatusBarUtil.setStatusBarColor(MainActivity.this,R.color.txtcode_color);
                                    //  StatusBarUtil.setStatusBarDarkTheme(MainActivity.this, true);
                                    break;
                              case 2:
                                    image.setVisibility(View.VISIBLE);
                                    //  simpleToolbar.setVisibility(View.GONE);
                                    // StatusBarUtil.setStatusBarColor(MainActivity.this,R.color.txtcode_color);
                                    break;
                        }
                  }

                  @Override
                  public void onPageSelected(int position) {

                  }

                  @Override
                  public void onPageScrollStateChanged(int state) {

                  }
            });
      }

      //权限申请
      @Override
      public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                             @NonNull int[] grantResults) {
            PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
      }

      @TargetApi(23)
      private void requestPermissions() {
            PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
                  @Override
                  public void onGranted() {
                        //  Toast.makeText(MainActivity.this, "All permissions have been granted", Toast.LENGTH_SHORT).show();
                  }

                  @Override
                  public void onDenied(String permission) {
                        //  Toast.makeText(MainActivity.this, "Permission " + permission + " has been denied", Toast.LENGTH_SHORT).show();
                  }
            });
      }


      private void init() {
            registerBroadcastReceiver();
            EMClient.getInstance().contactManager().setContactListener(new MyContactListener());
            EMClient.getInstance().addClientListener(clientListener);
            EMClient.getInstance().addMultiDeviceListener(new MyMultiDeviceListener());
            inviteMessgeDao = new InviteMessgeDao(this);
            UserDao userDao = new UserDao(this);
            //debug purpose only
            // registerInternalDebugReceiver();
      }

      EMClientListener clientListener = new EMClientListener() {
            @Override
            public void onMigrate2x(boolean success) {
                  Toast.makeText(MainActivity.this, "onUpgradeFrom 2.x to 3.x " + (success ? "success" : "fail"), Toast.LENGTH_LONG).show();
                  if (success) {
                        refreshUIWithMessage();
                  }
            }
      };

      private void refreshUIWithMessage() {
            runOnUiThread(new Runnable() {
                  public void run() {
                        // refresh unread count
                        updateUnreadLabel();
                        if (fragment != null && fragment instanceof MyconversationFragment) {
                              fragment.refresh();
                        } else if (fragment1 != null && fragment1 instanceof ContactListFragment) {
                              fragment1.refresh();
                        }
                  }


            });

      }


      public class MyContactListener implements EMContactListener {
            @Override
            public void onContactAdded(String username) {
            }

            @Override
            public void onContactDeleted(final String username) {
                  runOnUiThread(new Runnable() {
                        public void run() {
                              if (ChatActivity.activityInstance != null && ChatActivity.activityInstance.getToChatUsername() != null &&
                                        username.equals(ChatActivity.activityInstance.getToChatUsername())) {
                                    String st10 = getResources().getString(R.string.have_you_removed);
                                    Toast.makeText(MainActivity.this, ChatActivity.activityInstance.getToChatUsername() + st10, Toast.LENGTH_LONG)
                                              .show();
                                    ChatActivity.activityInstance.finish();
                              }
                        }
                  });
                  updateUnreadAddressLable();
            }

            @Override
            public void onContactInvited(String username, String reason) {
            }

            @Override
            public void onFriendRequestAccepted(String username) {
            }

            @Override
            public void onFriendRequestDeclined(String username) {
            }
      }

      public class MyMultiDeviceListener implements EMMultiDeviceListener {

            @Override
            public void onContactEvent(int event, String target, String ext) {

            }

            @Override
            public void onGroupEvent(int event, String target, final List<String> username) {
                  switch (event) {
                        case EMMultiDeviceListener.GROUP_LEAVE:
                              ChatActivity.activityInstance.finish();
                              break;
                        default:
                              break;
                  }
            }
      }


      private void registerBroadcastReceiver() {
            broadcastManager = LocalBroadcastManager.getInstance(this);
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
            intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED);
            broadcastReceiver = new BroadcastReceiver() {
                  @Override
                  public void onReceive(Context context, Intent intent) {
                        updateUnreadLabel();
                        updateUnreadAddressLable();
                        if (fragment != null){
                              if (fragment instanceof MyconversationFragment) {
                                    (fragment).refresh();
                              }
                              if (fragment1 instanceof ContactListFragment) {
                                    (fragment1).refresh();
                                    // ((ContactListFragment) fragment1).refresh();
                              }
                        }

                        String action = intent.getAction();
                        if (action.equals(Constant.ACTION_GROUP_CHANAGED)) {
                              if (EaseCommonUtils.getTopActivity(MainActivity.this).equals(GroupsActivity.class.getName())) {
                                    GroupsActivity.instance.onResume();
                              }
                        }

                  }

                  ;


            };
            broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
      }


      @Override
      protected void onResume() {
            super.onResume();
            try {
                  updateUnreadLabel();
                  updateUnreadAddressLable();
                  DemoHelper sdkHelper = DemoHelper.getInstance();
                  sdkHelper.pushActivity(this);
            } catch (Exception e) {

            }
            EMClient.getInstance().chatManager().addMessageListener(messageListener);
      }

      EMMessageListener messageListener = new EMMessageListener() {

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                  // notify new message
                  for (EMMessage message : messages) {
                        DemoHelper.getInstance().getNotifier().vibrateAndPlayTone(null);
                  }
                  refreshUIWithMessage();
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                  refreshUIWithMessage();
            }

            @Override
            public void onMessageRead(List<EMMessage> messages) {
            }

            @Override
            public void onMessageDelivered(List<EMMessage> message) {
            }

            @Override
            public void onMessageRecalled(List<EMMessage> messages) {
                  refreshUIWithMessage();
            }

            @Override
            public void onMessageChanged(EMMessage message, Object change) {
            }
      };

      public int getUnreadAddressCountTotal() {
            int unreadAddressCountTotal = 0;
            unreadAddressCountTotal = inviteMessgeDao.getUnreadMessagesCount();
            return unreadAddressCountTotal;
      }

      public void updateUnreadLabel() {
            int count = getUnreadMsgCountTotal();
            if (count > 0) {
                  indica2.setVisibility(View.VISIBLE);
            } else {
                  indica2.setVisibility(View.INVISIBLE);
            }
      }

      public int getUnreadMsgCountTotal() {
            return EMClient.getInstance().chatManager().getUnreadMsgsCount();
      }

      public void updateUnreadAddressLable() {
            runOnUiThread(new Runnable() {
                  public void run() {
                        int count = getUnreadAddressCountTotal();
                        if (count > 0) {
                              indica3.setVisibility(View.VISIBLE);
                        } else {
                              indica3.setVisibility(View.INVISIBLE);

                        }
                  }
            });

      }

      private void showiosDialog() {
            dialog = new CustomDialog(MyActivityManager.getInstance().getCurrentActivity(), R.style.customDialog, R.layout.login_out);
            dialog.show();
            TextView tvContent = (TextView) dialog.findViewById(R.id.textsign);
            tvContent.setText("该账号已在其他地方登录，您被迫下线");
            TextView tvOk = (TextView) dialog.findViewById(R.id.ok);
            tvOk.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {

                        dialog.dismiss();
                  }
            });

      }

      private void showiosDialog1() {
            dialog = new CustomDialog(MyActivityManager.getInstance().getCurrentActivity(), R.style.customDialog, R.layout.login_out);
            dialog.show();
            TextView tvContent = (TextView) dialog.findViewById(R.id.textsign);
            tvContent.setText("该账号已在其他地方登录，您被迫下线");
            TextView tvOk = (TextView) dialog.findViewById(R.id.ok);
            tvOk.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
                        dialog.dismiss();
                  }
            });

      }
}
